package com.keon.jianbao.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.R;
import com.keon.jianbao.adapter.UploadImgAdapter;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.widget.NoScrollGridView;
import com.keon.jianbao.util.DialogHelp;
import com.keon.jianbao.util.ImageUtils;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by keon on 2015/9/10.
 */
public class TweetPublishActivity extends BaseActivity {

    public static final int REQUEST_PICK_PHOTO = 1;
    public static final int MAX_UPLOAD_IMAGE_NUM = 6;

    UploadImgAdapter adapter;
    ArrayList<String> uploadImgs;

    String[] catlogs;
    String selectedCatlog;

    @Bind(R.id.tweet_publish_imgs)
    NoScrollGridView nsgvImage;
    @Bind(R.id.tweet_publish_catlog)
    Button bCatlog;
    @Bind(R.id.tweet_publish_content)
    EditText etContent;
    @Bind(R.id.tweet_publish_price)
    EditText etPrice;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    hideWaitDialog();
                    adapter.updateData(uploadImgs);
                    break;
            }
        }
    };

    SimpleHandler catlogHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    catlogs = JsonUtils.arrayFromJson(result.getContent());
                    bCatlog.setText(catlogs[0]);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler uploadImagesHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    JSONArray ja = new JSONArray(new JSONObject(result.getContent()).getString("images"));
                    String[] images = new String[ja.length()];
                    for (int i = 0; i < ja.length(); i++) {
                        images[i] = ja.get(i).toString();
                    }

                    showWaitDialog();
                    Api.add_tidings(bCatlog.getText().toString(), etContent.getText().toString(),
                            etPrice.getText().toString(), images, addTidingsHandler);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler addTidingsHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                showToast(result.getTips());
                if (result.getStatus() > 0) {
                    onBackPressed();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tweet_publish;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.tweet_publish;
    }

    @Override
    public void initView() {
        bCatlog.setOnClickListener(this);
        initGridView();
    }

    @Override
    public void initData() {
        catlogHandler.setContext(this);
        addTidingsHandler.setContext(this);
        uploadImagesHandler.setContext(this);

        showWaitDialog();
        Api.appraisal_catalog(catlogHandler);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tweet_publish_catlog:
                if (catlogs.length > 0) {
                    DialogHelp.getSingleChoiceDialog(this, catlogs, 0, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            selectedCatlog = catlogs[i];
                            bCatlog.setText(selectedCatlog);
                        }
                    }).show();
                } else {
                    showToast(R.string.common_error_network);
                    onBackPressed();
                }
                break;
        }
    }

    private void initGridView() {
        adapter = new UploadImgAdapter(MAX_UPLOAD_IMAGE_NUM);

        nsgvImage.setAdapter(adapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_PICK_PHOTO:
                final ArrayList<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//                uploadImgs = images;

                Thread t = new Thread() {
                    @Override
                    public void run() {
//                        super.run();
                        try {
                            uploadImgs = ImageUtils.getCompressImages(images);
                            handler.sendEmptyMessage(1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                };
                showWaitDialog("压缩图片中");
                t.start();
        /*        try {
                    uploadImgs = ImageUtils.getCompressImages(images);
                } catch (IOException e) {
                    e.printStackTrace();
                }*/

                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        return super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_tweet_publish, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.tweet_publish_submit:
                if (check()) {
                    try {
                        File[] imgs = new File[uploadImgs.size()];
                        for (int i = 0; i < uploadImgs.size(); i++) {
                            imgs[i] = new File(uploadImgs.get(i));
                        }
                        showWaitDialog();
                        Api.upload_tidings_images(AppContext.getInstance().getProperty("user.code"), imgs, uploadImagesHandler);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
//                TweetPublishActivity.showToast("11");
                break;
        }
        return true;
    }

    private boolean check() {

        if (uploadImgs != null && uploadImgs.size() > 0) {
        } else {
            showToast(R.string.upload_jianbao_image_error_null);
            return false;
        }

        if (StringUtils.isEmpty(etContent.getText().toString())) {
            showToast(R.string.tweet_publish_content_tip_null);
            return false;
        }

        if (!StringUtils.isPositiveDecimal(etPrice.getText().toString())) {
            showToast(R.string.tweet_publish_price_error);
            return false;
        }

        return true;
    }
}
